<?php

namespace app\api\model;

use app\common\enums\StatusEnum;

class OauthFocus extends \app\common\model\OauthFocus
{
    /**
     * 我的关注
     * @param $oauthId
     * @param $page
     * @param $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($oauthId, $page, $size)
    {
        $offset = ($page - 1) * $size;

        $sql = static::field('o.id AS uid, o.nickname, o.head_img AS headImg, o.signature, o.sex')
            ->alias('f')
            ->join('oauth o', 'f.focus_id = o.id', 'INNER')
            ->where([
                'f.oauth_id' => $oauthId,
                'o.status' => StatusEnum::ENABLED,
            ]);

        $model = $sql->order(['f.create_time' => 'desc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();

        return [
            'list' => $model,
            'count' => $sql->count()
        ];
    }

    /**
     * 获取一条关注记录
     * @param $oauthId
     * @param $focusId
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($oauthId, $focusId)
    {
        return static::field('id')
            ->where([
                'oauth_id' => $oauthId,
                'focus_id' => $focusId,
            ])->find();
    }

    /**
     * 添加一条记录
     * @param $oauthId
     * @param $focusId
     * @return mixed
     */
    public static function addOne($oauthId, $focusId)
    {
        $model = static::create([
            'oauth_id' => $oauthId,
            'focus_id' => $focusId
        ]);
        return isset($model->id) ? true : false;
    }

    /**
     * 取消关注
     * @param $oauthId
     * @param $focusId
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function deleteOne($oauthId, $focusId)
    {
        static::where([
            'oauth_id' => $oauthId,
            'focus_id' => $focusId
        ])->delete();
    }

    /**
     * 我的关注
     * @param $oauthId
     * @return float|string
     */
    public static function getCountMine($oauthId)
    {
        return static::field('id')
            ->alias('f')
            ->join('oauth o', 'f.focus_id = o.id', 'INNER')
            ->where([
                'f.oauth_id' => $oauthId,
                'o.status' => StatusEnum::ENABLED,
            ])
            ->count();
    }
}